require 'digest/sha1'

class PasswordController < ApplicationController
  
  layout 'account'
  
  verify :method => :post, :only => [:update_password],
         :redirect_to => {:action => 'recover_password'}
         
  verify :method => :post, :only => [:send_recovery],
         :redirect_to => {:action => 'fotget'}
         
  before_filter :check_token, :only => :recover_password
  
  def index
    fotget
    render :action => 'fotget'
  end
  
  def fotget
    @title = 'Fotget password'
  end
  
  def send_recovery
    @user = User.find_by_email(params[:email])
    
    if @user.nil?
      flash[:notice] = "This email didn\'t registered, please try again."
      render :action => 'fotget' and return
    end
    
    @pwd_recovery = @user.add_pwd_recovery
    
    begin @pwd_recovery.save!
      @recovery_mail = PasswordMailer.create_recovery(@pwd_recovery, params[:email])
      PasswordMailer.deliver(@recovery_mail)
      redirect_to :action => 'sent_success'
    rescue Exception => e
      flash[:notice] = e.message
      render :action => 'fotget'
    end
  end
  
  def sent_success
    @title = 'Success'
  end
  
  def recover_password
    @title = "Reset your password"
    @pwd_recovery = PasswordRecovery.find_by_token(params[:token])
    @user = @pwd_recovery.user
  end
  
  def update_password
    @user = User.find_by_id(params[:id])
    if @user.update_attributes(params[:user].symbolize_keys)
      redirect_to :action => 'recover_success'
    else
      render :action => 'recover_password'
    end
  end
  
  def recover_success
    @title = 'Success'
  end
  
  protected
  
  def check_token
    if !params[:token]
      redirect_to welcome_url and return false
    end
  end
  
  def check_id
    if !params[:id]
      redirect_to welcome_url and return false
    end
  end
  
end
